package settings;

import java.util.HashMap;

public final class SettingsReader {

    private static final String FLAG_PREFIX = "--";

    private static final HashMap<String, String> sArgs = new HashMap<String, String>();

    public static void loadArgs(String[] args) {
        sArgs.clear();
        for (int i = 0; i < args.length; ++i) {
            if (isValidArg(args[i])) {
                if (i+1 < args.length && !args[i+1].startsWith(FLAG_PREFIX)) {
                    // use [i+1] as value
                    sArgs.put(args[i++].substring(FLAG_PREFIX.length()), args[i]);
                } else {
                    // set as boolean value
                    sArgs.put(args[i].substring(FLAG_PREFIX.length()), String.valueOf(true));
                }
            }
        }
    }

    private static boolean isValidArg(String arg) {
        return arg.startsWith(FLAG_PREFIX) && arg.length() > FLAG_PREFIX.length();
    }

    public static boolean getBoolean(String name, boolean defaultValue) {
        boolean value = defaultValue;
        try {
            if (sArgs.containsKey(name)) {
                value = Boolean.parseBoolean(sArgs.get(name));
            }
        } catch (IllegalArgumentException ex) {}
        return value;
    }

    public static int getInteger(String name, int defaultValue) {
        int value = defaultValue;
        try {
            if (sArgs.containsKey(name)) {
                value = Integer.parseInt(sArgs.get(name));
            }
        } catch (IllegalArgumentException ex) {}
        return value;
    }

    public static long getLong(String name, long defaultValue) {
        long value = defaultValue;
        try {
            if (sArgs.containsKey(name)) {
                value = Long.parseLong(sArgs.get(name));
            }
        } catch (IllegalArgumentException ex) {}
        return value;
    }

    public static double getDouble(String name, double defaultValue) {
        double value = defaultValue;
        try {
            if (sArgs.containsKey(name)) {
                value = Double.parseDouble(sArgs.get(name));
            }
        } catch (IllegalArgumentException ex) {}
        return value;
    }

    public static String getString(String name, String defaultValue) {
        if (sArgs.containsKey(name)) {
            return sArgs.get(name);
        }
        return defaultValue;
    }
}
